package com.yingxin.yxerp.module.report.task.common.job.handle;

import com.yingxin.yx.framework.commons.constant.CommonConst;
import com.yingxin.yx.framework.commons.enums.task.DynamicTaskLogCategoryEnum;
import com.yingxin.yx.framework.commons.enums.task.DynamicTaskName;
import com.yingxin.yx.framework.commons.enums.task.DynamicTaskTypeEnums;
import com.yingxin.yx.framework.commons.id.IdHelper;
import com.yingxin.yxerp.module.report.entity.DynamicTaskLog;
import com.yingxin.yxerp.module.report.entity.enums.DynamicTaskLogStatusEnums;
import com.yingxin.yxerp.module.report.service.IDynamicTaskLogService;
import com.yingxin.yxerp.module.report.task.vo.resp.DynamicTaskRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * job log handle
 */

@Service
public class JobHandle {

    @Autowired
    private IDynamicTaskLogService logService;

    /**
     * 处理基本信息
     * @param vo
     * @return
     */
    public DynamicTaskLog handle(DynamicTaskRespVo vo, String category ){
        DynamicTaskLog log = new DynamicTaskLog();
        log.setId( IdHelper.snowflakeId() );
        // 来源
        log.setCategoryType( category );
        log.setCategory( DynamicTaskLogCategoryEnum.getEnum( category ).getTypeName() );
        log.setTaskId( vo.getId() );
        // 任务分类
        log.setTaskType( vo.getTaskType() );
        log.setTaskTypeName( DynamicTaskTypeEnums.getEnum( vo.getTaskType() ).getTypeName() );
        // 任务名称
        log.setTaskNameType( vo.getTaskName() );
        log.setTaskName(DynamicTaskName.getEnum( vo.getTaskName() ).getTypeName() );
        log.setCreatorId( CommonConst.TRUE );
        log.setUpdaterId( CommonConst.TRUE );

        // 任务状态
        log.setStatus( DynamicTaskLogStatusEnums.EXECUTING.getStatus() );

        // 开始时间
        log.setStartTime( new Date() );
        log.setDelFlag( CommonConst.FALSE );

        logService.saveLog( log );

        return log;
    }

    /**
     * 处理结束时间，执行时长
     * @param log
     */
    public void processingTime(DynamicTaskLog log, String msg, Integer status ){
        log.setStatus( status );
        log.setMsg( msg );
        log.setEndTime( new Date() );
        log.setSpendTime( log.getEndTime().getTime() - log.getStartTime().getTime() );

        logService.updateById( log );
    }

}
